/**
 * 
 */
package com.res.simulator.handler;

import java.util.List;

import org.apache.log4j.Logger;

import com.res.common.handler.CommonHandler;
import com.res.simulator.view.SearchResultView;
import com.res.simulator.plugins.MessageCommunicationClientPlugin;
import com.res.simulator.transformer.RecordedAPIInvocationTransformer;
import com.res.simulator.view.RecordAndPlayExecutionResultView;
import com.res.system.utils.SimulatorUtilities;
import com.res.system.utils.SimulatorUtilities.ConfigData;
import com.sip.comserver.communication.CommunicationMessage;
import com.sip.dbadapter.dao.domain.ScenarioRecord;

/**
 * @author mg40327
 */
public class RecordedAPIInvocationHandler implements CommonHandler<List<RecordAndPlayExecutionResultView>, List<SearchResultView>> {

    private static final Logger logger = Logger.getLogger(RecordedAPIInvocationHandler.class);

    public List<RecordAndPlayExecutionResultView> process(List<SearchResultView> searchResultViewmodel) throws Exception {

        final RecordedAPIInvocationTransformer restTransformer = new RecordedAPIInvocationTransformer();
        final List<ScenarioRecord> domainList = restTransformer.transformModelToDomian(searchResultViewmodel);
        logger.info("===============Inside RecordedAPIInvocationHandler========>" + domainList.size());

        final List<ScenarioRecord> returnList = commit(domainList);
        final List<RecordAndPlayExecutionResultView> resultView = restTransformer.transformDomianToView(returnList);

        return resultView;
    }

    private List<ScenarioRecord> commit(final List<ScenarioRecord> domainList) throws Exception {

        final CommunicationMessage message = new CommunicationMessage();

        final String serverAddress = SimulatorUtilities.getConfigData(ConfigData.SERVER_ADDRESS);
        final String port = SimulatorUtilities.getConfigData(ConfigData.SERVER_PORT);

        String executorName = "RecordedServicesExecute";
        logger.info("Message Header==>" + "JOBType:BatchExecute" + "|ID:" + serverAddress + "|Port:" + port + "|Executor:" + executorName);

        message.setMessageHeader("JOBType:BatchExecute|Executor:" + executorName + "|ID:" + serverAddress + "|Port:" + port);
        message.setObject(domainList);

        final MessageCommunicationClientPlugin plugin = new MessageCommunicationClientPlugin();
        final CommunicationMessage returnedMessage = plugin.invoke(message);

        final List<ScenarioRecord> returnList = (List<ScenarioRecord>) returnedMessage.getObject();

        return returnList;

    }
}
